package com.event.handler;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.event.exception.TokenException;
import com.event.exception.UserException;
import com.event.result.Result;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
	
	/**
	 * 捕获业务异常
	 */
	@ExceptionHandler
	public Result<String> exceptionHandler(Exception e) {
		String message = e.getMessage();
		if (message.contains(TokenException.TOKEN_INVALID)) {
			return Result.error(TokenException.TOKEN_INVALID);
		} else if (message.contains("The Token has expired")) {
			return Result.error(TokenException.TOKEN_EXPIRED);
		}
		log.error("异常信息：{}", message);
		return Result.error(message);
	}
	
	/**
	 * 捕获SQLIntegrityConstraintViolationException异常
	 */
//	@ExceptionHandler
//	public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
//		log.error("异常信息：{}", ex.getMessage());
//		String message = ex.getMessage();
//		if (message.contains("Duplicate entry")) {
//			return Result.error(message.split(" ")[2].split("'")[1] + MessageConstant.ALREADY_EXISTS);
//		}
//		return Result.error(MessageConstant.UNKNOWN_ERROR);
//	}
	@ExceptionHandler
	public Result<String> violationHandler(ConstraintViolationException e) {
		String message = e.getMessage();
		log.error("异常信息：{}", message);
		if (message.contains("username") && !message.contains("password")) {
			return Result.error(UserException.UAERNAME_LENGTH_ERROR);
		}
		if (message.contains("password") && !message.contains("username")) {
			return Result.error(UserException.PASSWORD_LENGTH_ERROR);
		}
		if (message.contains("username") && message.contains("password")) {
			return Result.error(UserException.USERNAME_PASSWORD_NOT_NULL);
		}
		return Result.error(message);
	}
	
	/**
	 * 捕获JWTDecodeException异常
	 * token不存在
	 */
	@ExceptionHandler
	public Result<String> TokenExceptionHandler(JWTDecodeException e) {
		return Result.error(TokenException.TOKEN_NOT_FOUND);
	}
	
	/**
	 * 捕获SignatureVerificationException异常
	 * token已过期
	 */
	@ExceptionHandler
	public Result<String> TokenExceptionHandler(SignatureVerificationException e) {
		return Result.error(TokenException.TOKEN_EXPIRED);
	}
}
